package logic

import (
	"context"
	"fmt"
	"strconv"
	"taobao/cache"

	"taobao/taobaorpc/internal/svc"
	"taobao/taobaorpc/taobaorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartListLogic {
	return &CartListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartListLogic) CartList(in *taobaorpc.CartListRequest) (*taobaorpc.CartListResponse, error) {
	// todo: add your logic here and delete this line
	key := fmt.Sprintf("cart:%d:*", in.UserId)
	keys, _ := cache.Rdb.Keys(l.ctx, key).Result()
	PriceAll := 0.0
	var lists []*taobaorpc.CartList
	for _, key1 := range keys {
		result, _ := cache.Rdb.HGetAll(l.ctx, key1).Result()
		price, _ := strconv.Atoi(result["price"])
		Number, _ := strconv.Atoi(result["number"])
		UserId, _ := strconv.Atoi(result["userId"])
		TotalPrice := Number * price
		PriceAll += float64(TotalPrice)
		list := taobaorpc.CartList{
			Name:       result["name"],
			Price:      float32(price),
			Number:     int64(Number),
			UserId:     int64(UserId),
			TotalPrice: int64(TotalPrice),
		}
		lists = append(lists, &list)
	}
	return &taobaorpc.CartListResponse{
		List:     lists,
		PriceAll: float32(PriceAll),
	}, nil
}
